﻿namespace SecutityLib
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// Ceaser Cipher class 
    /// </summary>
    public class CeaserCipher : EncodingDecodingTech
    {
        /// <summary>
        /// Encodes the specified plain text.
        /// </summary>
        /// <param name="plainText">The plain text.</param>
        /// <param name="key">The key.</param>
        /// <returns>cipher text</returns>
        public override string Encode(string plainText, string key)
        {
            string cipher = string.Empty;
            int cnt = plainText.Length;
            int ceaserKey;
            try
            {
                ceaserKey = int.Parse(key);
            }
            catch
            {
                throw new System.Exception("Invalid Key (Must be an integer)");
            }

            if (ceaserKey < 0 || ceaserKey > 26)
            {
                throw new System.Exception("key value must be between 0 and 26");
            }

            for (int i = 0; i < cnt; i++)
            {
                cipher += (char)((plainText[i] + ceaserKey) > 'z' ? (plainText[i] + ceaserKey) - 26 : (plainText[i] + ceaserKey));
            }

            return cipher;
        }

        /// <summary>
        /// Decodes the specified plain text.
        /// </summary>
        /// <param name="cipherText">the cipher text</param>
        /// <param name="key">The key.</param>
        /// <returns>
        /// cipher text
        /// </returns>
        public override string Decode(string cipherText, string key)
        {
            string plain = string.Empty;
            int cnt = cipherText.Length;
            int ceaserKey;
            try
            {
                ceaserKey = int.Parse(key);
            }
            catch
            {
                throw new System.Exception("Invalid Key (Must be an integer)");
            }

            if (ceaserKey < 0 || ceaserKey > 26)
            {
                throw new System.Exception("key value must be between 0 and 26");
            }

            for (int i = 0; i < cnt; i++)
            {
                plain += (char)((cipherText[i] - ceaserKey) < 'a' ? (cipherText[i] - ceaserKey) + 26 : (cipherText[i] - ceaserKey));
            }

            return plain;
        }
    }
}
